package com.wdz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wdz.category.entity.Category;
import com.wdz.category.service.ICategoryService;
import com.wdz.http.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService iCategoryService;

    /**
     * 根据分类等级查询分类集合
     */
    @PostMapping("/queryListByLevel")
    public Response queryListByLevel(@RequestParam Integer level){
        return Response.success(iCategoryService.selectList(new EntityWrapper<Category>().where("level={0} and type=1",level)));
    }
    /**
     * 根据分类等级分页查询分类集合
     */
    @PostMapping("/queryPageListByLevel")
    public Response queryPageListByLevel(@RequestParam Integer level,@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        Map<String,Object> data = new HashMap<>();
        Wrapper<Category> wrapper = new EntityWrapper<Category>().where("level={0} and type=1",level);
        data.put("total",iCategoryService.selectCount(wrapper));
        data.put("data",iCategoryService.selectPage(new Page<>(pageNo,pageSize),wrapper).getRecords());
        return Response.success(data);
    }
    /**
     * 添加分类
     */
    @PostMapping("/addCategory")
    public Response addCategory(@RequestBody Category category){
        if(iCategoryService.selectCount(new EntityWrapper<Category>().where("name={0} and type=1 and level={1}",category.getName(),category.getLevel())) > 0){
            return Response.error("当前分类等级下的分类名已存在");
        }
        iCategoryService.insert(category);
        return Response.success((Object) category.getId());
    }
    /**
     * 查询单个分类
     */
    @PostMapping("/queryCategory")
    public Response queryCategory(@RequestParam String id){
        return Response.success(iCategoryService.selectById(id));
    }
    /**
     * 删除单个分类
     */
    @DeleteMapping("/{id}")
    public Response delete(@PathVariable String id){iCategoryService.deleteById(id); return Response.success();}
}
